package com.lyy.exception;


import com.lyy.result.Result;
import com.lyy.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author liangyaoyun
 */
@Slf4j
@RestControllerAdvice("com.lyy")
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result validationException(MethodArgumentNotValidException e) {

        // 获取实体参数绑定结果
        BindingResult bindingResult = e.getBindingResult();

        // 判断bindingResult中是否存在校验失败的信息
        if (bindingResult.hasErrors()) {

            // 获取bindingResult中所有属性错误信息集合中的第一个属性错误
            FieldError firstFieldError = bindingResult.getFieldErrors().get(0);

            // 响应 "xxx实例的xxx属性校验失败: xxx异常信息"
            String obj = firstFieldError.getObjectName();
            String field = firstFieldError.getField();
            String message = firstFieldError.getDefaultMessage();
            return new Result(ResultCode.VALIDATE_FAILED, obj + "的" + field + "校验失败: " + message);
        }

        // 返回其他异常信息
        return new Result(ResultCode.FAILED, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        log.info("全局异常", e);
        return new Result(ResultCode.FAILED, e.getMessage());
    }
}